package org.dromara.tearoom.service.impl;

import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.tearoom.domain.GeeOpenDevice;
import org.dromara.tearoom.domain.bo.TerIotDeviceOperLogBo;
import org.dromara.tearoom.mqtt.BreakerDataRequest;
import org.dromara.tearoom.service.IBreakerCommandService;
import org.dromara.tearoom.service.ITerIotDeviceOperLogService;
import org.dromara.tearoom.service.ITerIotDeviceService;
import org.dromara.tearoom.util.MqttUtil;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.stereotype.Service;

/**
 * @author CKJ
 * @description: TODO
 * @date 2025/4/15 18:22
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class GeeOpenCommandServiceImpl implements IBreakerCommandService {
    private final ITerIotDeviceService terIotDeviceService;
    private final ITerIotDeviceOperLogService terIotDeviceOperLogService;


    @Override
    public boolean commandBreaker(BreakerDataRequest breakerDataRequest, boolean isAuto , boolean isLog) {
        log.info("执行的是GeeOpen设备的命令");
        MqttUtil.sendMqttMsg(breakerDataRequest.getMqttSubscribe(), breakerDataRequest.getCommand());
        writeLog(breakerDataRequest,isLog);
        return true;
    }

    @Override
    public boolean commandBreaker(BreakerDataRequest breakerDataRequest, boolean isLog) {
        return commandBreaker(breakerDataRequest, false, isLog);
    }

    //写入日志 isLog 是否写入
    private void writeLog(BreakerDataRequest breakerDataRequest, boolean isLog) {
        if (isLog) {
            String[] segments = breakerDataRequest.getMqttSubscribe().split("/");
            TerIotDeviceOperLogBo bo = new TerIotDeviceOperLogBo();
            bo.setDeviceKey(segments[3]);
            bo.setOperation(breakerDataRequest.getCommand());
            bo.setType(breakerDataRequest.getOperaType());
            terIotDeviceOperLogService.insertByBo(bo);
        }

    }

    @Override
    public boolean commandGatewayTimeReporting(String gatewayCode, int minute) {
        BreakerDataRequest breakerDataRequest = new BreakerDataRequest();
        return commandBreaker(breakerDataRequest, false);
    }

    @Override
    public void breakerCallback(String topic, MqttMessage mqttMessage) {
        String payload = new String(mqttMessage.getPayload());
        log.info("收到GeeOpen设备的消息了:{}",payload);
        if(payload.contains("mac")){
            GeeOpenDevice geeOpenDevice= JSONUtil.toBean(payload,GeeOpenDevice.class);
            terIotDeviceService.updateByDeviceKey(geeOpenDevice);
        }
    }

    @Override
    public boolean commandBreakerBatch(BreakerDataRequest breakerDataRequest) {
        return false;
    }



    //验证远程操作指令
    private boolean checkingCommandData(BreakerDataRequest breakerDataRequest) {
        return true;
    }

    //拼装数据
    private String getCommandData(BreakerDataRequest breakerDataRequest, String type) {
        return null;
    }

}
